package org.mybatis.generator.plugins;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

public class MyBaseMapperGeneratorPlugin extends PluginAdapter {

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
    }

    public boolean validate(List<String> warnings) {
		return true;
	}

	/**
	 * 生成dao
	 */
	@Override
	public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,
			IntrospectedTable introspectedTable) {
        String columnsType="java.lang.String";
        //动态获取当前表的主键类型，如果有联合主键，默认取联合主键的第一列（可能存在问题）
        //主键为空则默认为String类型
        if(introspectedTable.getPrimaryKeyColumns()!=null && introspectedTable.getPrimaryKeyColumns().size()>0){
            columnsType=introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
        }
        String  baseDaoPath=properties.get("baseDaoPath").toString();

        /**
         * 主键默认采用java.lang.Integer
         */
        FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(baseDaoPath.substring(baseDaoPath.lastIndexOf(".")+1,baseDaoPath.length())+"<" + introspectedTable.getBaseRecordType()
                + "," + introspectedTable.getExampleType() + "," + columnsType + ">");

        FullyQualifiedJavaType imp = new FullyQualifiedJavaType(baseDaoPath);
        /**
         * 添加 extends MybatisBaseMapper
         */
        interfaze.addSuperInterface(fqjt);

        /**
         * 添加import my.mabatis.example.base.MybatisBaseMapper;
         */
        interfaze.addImportedType(imp);
        /**
         * 方法不需要
         */
        interfaze.getMethods().clear();
        interfaze.getAnnotations().clear();
        return true;
    }
}
